package com.tanhua.server.service;

import com.tanhua.autoconfig.templates.OssTemplate;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.Comment;
import com.tanhua.domain.mongo.Movement;
import com.tanhua.domain.mongo.Visitors;
import com.tanhua.dubbo.api.db.UserInfoApi;
import com.tanhua.dubbo.api.mongo.CommentApi;
import com.tanhua.dubbo.api.mongo.MovementApi;
import com.tanhua.dubbo.api.mongo.RecommendUserApi;
import com.tanhua.dubbo.api.mongo.VisitorsApi;
import com.tanhua.server.exceptions.TanhuaException;
import com.tanhua.server.interceptors.UserHolder;
import com.tanhua.server.utils.RelativeDateFormat;
import com.tanhua.vo.MovementsVo;
import com.tanhua.vo.PageResult;
import com.tanhua.vo.RecommendUserVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.rocketmq.spring.core.RocketMQTemplate;
import org.bson.types.ObjectId;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class MovementService {

    @Autowired
    private OssTemplate ossTemplate;
    @Autowired
    private StringRedisTemplate redisTemplate;

    @Reference
    private MovementApi movementApi;

    @Reference
    private UserInfoApi userInfoApi;
    @Reference
    private CommentApi commentApi;

    @Autowired
    private RocketMQTemplate rocketMQTemplate;


    public ResponseEntity saveMovements(Movement movement, MultipartFile[] imageContent) throws Exception {
        //发布动态冻结
        UserInfo user = userInfoApi.findById(UserHolder.getUserId());
        if (user != null){
            Long userId = user.getId();
            String userStatus = user.getUserStatus();
            //暂时
            String freezingRange = redisTemplate.boundValueOps("FREEZE_KEY_"+userId.toString()).get();
            //永久
            String freezingRangePlus = redisTemplate.boundValueOps("FREEZEFOREVER_KEY_"+userId.toString()).get();
            //冻结创建时间
            String freezeCreated = redisTemplate.boundValueOps("freezeCreated" + userId.toString()).get();
            //冻结时间
            String freezingTime = redisTemplate.boundValueOps("freezingTime" + userId.toString()).get();
            //逻辑判断被冻结（1 冻结登录，2 冻结发言，3 冻结发布动态）
            if (freezingRange == null) {
                userInfoApi.updateById(userId);
            }
            //逻辑判断 如果用户状态等于2（“封禁”）
            //因为不涉及登录，所有排除登录封禁
            if (StringUtils.equals(userStatus,"2")){
                if (StringUtils.equals(freezingRange,"3")){
                    //直接显示冻结时间
                    throw new TanhuaException(500,"你的账户于"+freezeCreated+"，限制发布动态为期："+freezingTime+"天");
                }else if (StringUtils.equals(freezingRangePlus,"forever")){//或者为永久封禁
                    throw new TanhuaException(500,"被永久冻结");
                }
            }
        }
//        1、上传图片返回url
        List<String> medias = new ArrayList<>();
        for (MultipartFile multipartFile : imageContent) {
            String picUrl = ossTemplate.upload(multipartFile.getOriginalFilename(), multipartFile.getInputStream());
            medias.add(picUrl);
        }

        movement.setMedias(medias);
        movement.setUserId(UserHolder.getUserId());
//        2、向mongo传一个movement对象
        String movementId = movementApi.saveMovements(movement);

        rocketMQTemplate.convertAndSend("movement_huawei_check",movementId);


        return ResponseEntity.ok(null);

    }

    public ResponseEntity queryFriendMovements(Integer page, Integer pagesize) {
//        1、查询mongo的服务 返回PageResult<Movement>
//        movement_friend_USERID
        PageResult pageResult =  movementApi.queryFriendMovements(UserHolder.getUserId(),page,pagesize);
        List<Movement> movementList = (List<Movement>) pageResult.getItems();

        List<MovementsVo> list = new ArrayList<>();
//        2、根据Movement中的userId查询 UserInfo
        for (Movement movement : movementList) {
            Long userId = movement.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);
//      3、Movement+UserInfo--->MovementsVo
            MovementsVo movementsVo = movementAndUserInfoToMovementsVo(movement, userInfo);

            list.add(movementsVo);
        }

        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);


    }

    public ResponseEntity queryRecommendMovements(Integer page, Integer pagesize) {
        //        1、查询mongo的服务 返回PageResult<Movement>
//        Recommend_Movement
        PageResult pageResult =  movementApi.queryRecommendMovements(UserHolder.getUserId(),page,pagesize);
        List<Movement> movementList = (List<Movement>) pageResult.getItems();

        List<MovementsVo> list = new ArrayList<>();
//        2、根据Movement中的userId查询 UserInfo
        for (Movement movement : movementList) {
            Long userId = movement.getUserId();
            UserInfo userInfo = userInfoApi.findById(userId);
//      3、Movement+UserInfo--->MovementsVo
            MovementsVo movementsVo = movementAndUserInfoToMovementsVo(movement, userInfo);

            list.add(movementsVo);
        }

        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);



    }

    public MovementsVo movementAndUserInfoToMovementsVo(Movement movement, UserInfo userInfo) {
        MovementsVo movementsVo = new MovementsVo();

        BeanUtils.copyProperties(userInfo, movementsVo);
        movementsVo.setId(movement.getId().toString()); //动态id
        movementsVo.setUserId(userInfo.getId());
        if (StringUtils.isNotBlank(userInfo.getTags())) {
            movementsVo.setTags(userInfo.getTags().split(","));
        }

        BeanUtils.copyProperties(movement, movementsVo);
        movementsVo.setImageContent(movement.getMedias().toArray(new String[]{}));
        movementsVo.setDistance("500米");
        movementsVo.setCreateDate(RelativeDateFormat.format(new Date(movement.getCreated())));

//        redisTemplate.boundValueOps("publish_like_"+UserHolder.getUserId()+"_"+movementId).set("");


        if(redisTemplate.hasKey("publish_like_"+UserHolder.getUserId()+"_"+movement.getId().toString())){
            movementsVo.setHasLiked(1); // 判断当前登录人对这个圈子是否点赞
        }else{
            movementsVo.setHasLiked(0);
        }

        if(redisTemplate.hasKey("publish_love_"+UserHolder.getUserId()+"_"+movement.getId().toString())){
            movementsVo.setHasLoved(1); // 判断当前登录人对这个圈子是否喜欢
        }else{
            movementsVo.setHasLoved(0);
        }
        return movementsVo;
    }

    public ResponseEntity queryMyselfMovements(Long userId, Integer page, Integer pagesize) {
        //        1、查询mongo的服务 返回PageResult<Movement>

        if(userId==null){
            userId = UserHolder.getUserId();
        }
//        movement_mine_USERID
        PageResult pageResult =  movementApi.queryMyselfMovements(userId,page,pagesize);
        List<Movement> movementList = (List<Movement>) pageResult.getItems();

        List<MovementsVo> list = new ArrayList<>();

        UserInfo userInfo = userInfoApi.findById(userId); //查询发布圈子的用户信息
//        2、根据Movement中的userId查询 UserInfo
        for (Movement movement : movementList) {
//      3、Movement+UserInfo--->MovementsVo
            MovementsVo movementsVo = movementAndUserInfoToMovementsVo(movement, userInfo);
            list.add(movementsVo);
        }

        pageResult.setItems(list);

        return ResponseEntity.ok(pageResult);




    }

    public ResponseEntity like(String movementId) {
//        1、保存点赞数据
        Comment comment = new Comment();
        comment.setCommentType(1); // 1-动态点赞，2-动态评论，3-动态喜欢 4-视频点赞  5-视频评论  6-评论点赞
        comment.setPublishId(new ObjectId(movementId)); //
        comment.setUserId(UserHolder.getUserId());
//        2、对圈子点赞数+1
//        3、返回这个圈子的点赞数
       Integer count = commentApi.saveComment(comment);

//       当前登录人对这个圈子点赞  在redis中做一个标记
        redisTemplate.boundValueOps("publish_like_"+UserHolder.getUserId()+"_"+movementId).set("");


       return ResponseEntity.ok(count);

    }

    public ResponseEntity dislike(String movementId) {
        //        1、取消点赞数据
        Comment comment = new Comment();
        comment.setCommentType(1); // 1-动态点赞，2-动态评论，3-动态喜欢 4-视频点赞  5-视频评论  6-评论点赞
        comment.setPublishId(new ObjectId(movementId)); //
        comment.setUserId(UserHolder.getUserId());
//        2、返回这个圈子的点赞数
        Integer count = commentApi.deleteComment(comment);
        redisTemplate.delete("publish_like_"+UserHolder.getUserId()+"_"+movementId);
        return ResponseEntity.ok(count);
    }

    public ResponseEntity love(String movementId) {
        //        1、保存喜欢数据
        Comment comment = new Comment();
        comment.setCommentType(3); // 1-动态点赞，2-动态评论，3-动态喜欢 4-视频点赞  5-视频评论  6-评论点赞
        comment.setPublishId(new ObjectId(movementId)); //
        comment.setUserId(UserHolder.getUserId());
//        2、对圈子喜欢数+1
//        3、返回这个圈子的喜欢数
        Integer count = commentApi.saveComment(comment);

//       当前登录人对这个圈子喜欢  在redis中做一个标记
        redisTemplate.boundValueOps("publish_love_"+UserHolder.getUserId()+"_"+movementId).set("");


        return ResponseEntity.ok(count);
    }

    public ResponseEntity unlove(String movementId) {

        //        1、取消喜欢数据
        Comment comment = new Comment();
        comment.setCommentType(3); // 1-动态点赞，2-动态评论，3-动态喜欢 4-视频点赞  5-视频评论  6-评论点赞
        comment.setPublishId(new ObjectId(movementId)); //
        comment.setUserId(UserHolder.getUserId());
//        2、返回这个圈子的喜欢数
        Integer count = commentApi.deleteComment(comment);
        redisTemplate.delete("publish_love_"+UserHolder.getUserId()+"_"+movementId);
        return ResponseEntity.ok(count);
    }

    public ResponseEntity queryMovementById(String movementId) {

//        mongo  Movement
        Movement movement = movementApi.queryMovementById(movementId);
//        mysql UserInfo
        Long userId = movement.getUserId();
        UserInfo userInfo = userInfoApi.findById(userId);

        MovementsVo movementsVo = movementAndUserInfoToMovementsVo(movement, userInfo);
        return ResponseEntity.ok(movementsVo);


    }

    @Reference
    private VisitorsApi visitorsApi;
    @Reference
    private RecommendUserApi recommendUserApi;
    public ResponseEntity queryVisitors(int size) {

//        获取上一次访问的时间Long   select * from visitors where  created > 上一次访问的时间Long  limit 4  order by  created desc

        String visiteTimeStr = redisTemplate.boundValueOps("visitors_" + UserHolder.getUserId()).get();

        List<Visitors> visitorsList = null;

        if(visiteTimeStr!=null){
            Long visiteTime = Long.parseLong(visiteTimeStr);
           visitorsList = visitorsApi.queryVisitors(UserHolder.getUserId(),size,visiteTime);
        }else{
           visitorsList =  visitorsApi.queryVisitors(UserHolder.getUserId(),size);
        }

        List<RecommendUserVo> list = new ArrayList<>();
        for (Visitors visitors : visitorsList) {
            Long visitorUserId = visitors.getVisitorUserId();
            UserInfo userInfo = userInfoApi.findById(visitorUserId);

            RecommendUserVo recommendUserVo = new RecommendUserVo();

            BeanUtils.copyProperties(userInfo,recommendUserVo);

            if(userInfo.getTags()!=null){
                recommendUserVo.setTags(userInfo.getTags().split(","));
            }
            Long score = recommendUserApi.queryScore(UserHolder.getUserId(),visitorUserId);
            recommendUserVo.setFateValue(score); //两个人（当前登录人和userId）的缘分值

            list.add(recommendUserVo);

        }

        redisTemplate.boundValueOps("visitors_" + UserHolder.getUserId()).set(new Date().getTime()+"");

        return ResponseEntity.ok(list);


    }
}
